//
//  SinaOAuthVC.swift
//  mySina
//
//  Created by 刘莹 on 2016/11/15.
//  Copyright © 2016年 liuying. All rights reserved.
//展示登录网页

import UIKit
import SVProgressHUD
//用户信息存储路径
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account2.plist")

class SinaOAuthVC: UIViewController{
    //MARK: -
    //MARK: - 定义属性
    let webView = UIWebView()
    override func loadView() {
        view = webView//指定根视图
        webView.delegate = self;//指定代理
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName: nil, target: self, action: #selector(close))
        //测试用
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "走后门", imageName: nil, target: self, action: #selector(fillAccount))
        //设置背景颜色:手写代码创建的控制器背景色是透明的
        self.view.backgroundColor = UIColor.white
        //请求授权页面
        loadOauthPage()
        
    }
    //MARK: -
    //MARK: - 加载新浪登陆页面
    private func loadOauthPage(){
        let urlString =  "https://api.weibo.com/oauth2/authorize?client_id="+client_id+"&redirect_uri="+redirect_uri
        let url = URL(string: urlString)
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
    }
    //MARK: -
    //MARK: - 填充账号
    @objc private func fillAccount(){
    
        let jsString = "document.getElementById('userId').value = '3460665993@qq.com',document.getElementById('passwd').value = '1256924534'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    //MARK: -
    //MARK: - 关闭新浪登陆页面
    @objc private func close(){
    
        dismiss(animated: true, completion: nil)
    }
    //MARK: -
    //MARK: - 在页面关闭的时候dismiss掉指示器(当网络请求已发出,服务器正在做出响应时,此时关闭页面,会导致菊花依然在转)
    override func viewWillDisappear(_ animated: Bool) {
        
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    
       override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension SinaOAuthVC:UIWebViewDelegate{
    //MARK: -
    //MARK: - webView协议中的代理方法
    //MARK: -
    //MARK: - 开始加载请求
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    //MARK: -
    //MARK: - 加载请求完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    //MARK: -
    //MARK: - 加载请求失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.dismiss()
    }
    //MARK: - 1.用户点击授权获取code
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //        http://www.itcast.cn/?code=839333a8b7ac494f43ace1dcd9550919
        let urlString = request.url?.absoluteString ?? ""
        //print(urlString)
        let flag = "code="
        if urlString.contains(flag) {//如果包含,说明能够截取code
            let query = request.url?.query ?? ""
            let code = (query as NSString).substring(from: flag.characters.count)
            // print(code)
            ////如果code获取成功,再通过code获取toketn
//            loadAccessToken(code: code)
            SinaUserAccountViewModel.shared.loadAccessToken(code: code, finished: { (isSuccess:Bool) in
                if !isSuccess{//没有成功
                    
                    SVProgressHUD.showError(withStatus: errorTip)
                    return
                    
                }
                
                //print("请求成功")
//                切换根视图控制器 ->欢迎页面(不方便维护)
//                UIApplication.shared.keyWindow?.rootViewController = SinaWelcomVC()
                
                //object:表示哪个对象发通知,通常用来传参数
                NotificationCenter.default.post(name: NSNotification.Name(kChoseRootViewController), object: "Welcome")
            
            
            })
            return false//code 获取成功后不加载页面
            
        }
        return true
    }
    
    
    
    
    
    
    
    
}
